<template>
  <el-dialog
      v-model="dialogVisible"
      :destroy-on-close="true"
      title="订单详情"
      width="80%"
      @close="handleClose"
  >
    <el-row :gutter="20">
      <!-- 左侧订单状态和基本信息 -->
      <el-col :span="8">
        <el-card class="h-full">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="font-bold flex">
                <el-icon :size="20">
                <Tickets/>
              </el-icon>
                订单状态
              </span>
              <el-tag :type="getStatusType">{{ getStatusText }}</el-tag>
            </div>
          </template>

          <el-timeline>
            <el-timeline-item
                v-if="orderData.createTime"
                :timestamp=orderData.createTime
                type="success"
            >
              <span>订单已下单</span>
              <p>订单号: {{ orderData.orderNo }}</p>
            </el-timeline-item>

            <el-timeline-item
                v-if="orderData.payTime"
                :timestamp="orderData.payTime"
                type="success"
            >
              <span>订单已支付</span>
              <p>支付方式: '微信支付'</p>
            </el-timeline-item>

            <el-timeline-item
                v-if="orderData.status >= 3"
                :timestamp=orderData.createTime
                type="success"
            >
              <span>商家已发货</span>
            </el-timeline-item>

            <el-timeline-item
                v-if="orderData.finishTime"
                :timestamp=orderData.finishTime
                type="success"
            >
              <h4>订单已完成</h4>
            </el-timeline-item>
          </el-timeline>

          <div class="mt-4">
            <el-descriptions :column="1" border title="订单信息">
              <el-descriptions-item label="订单金额">
                ¥ {{ orderData.totalPrice }}
              </el-descriptions-item>
              <el-descriptions-item label="订单号">
                {{ orderData.orderNo }}
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <div v-if="orderData.status === 1" class="mt-4 flex justify-center">
            <base-image :src="orderData.payCodeUrl"></base-image>
          </div>

          <el-form
              v-if="orderData.hasShipRole"
              ref="shipFormRef"
              :rules="shipRules"
              :model="orderShip"
              label-width="100px"
              style="margin-top: 10px"
          >
            <el-form-item label="配送员" prop="deliveryPerson">
              <el-input v-model="orderShip.deliveryPerson" placeholder="输入配送员"></el-input>
            </el-form-item>
            <el-form-item label="配送员电话" prop="deliveryPhone">
              <el-input v-model="orderShip.deliveryPhone" placeholder="输入配送员电话"></el-input>
            </el-form-item>
          </el-form>

          <!-- 操作按钮 -->
          <div class="mt-4 flex justify-center">
            <el-button
                v-if="orderData.status === 2 && store.state.userInfo.role !== 'user'"
                type="warning"
                @click="handleShip"
            >
              <el-icon>
                <Van/>
              </el-icon>
              确认发货
            </el-button>
            <el-button
                v-if="orderData.status === 3 && role === 'user'"
                type="success"
                @click="handleReceive"
            >
              <el-icon><Select/></el-icon>
              确认收货
            </el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧商品列表 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="font-bold">商品信息</div>
          </template>

          <div class="space-y-4">
            <div v-for="item in orderItems" :key="item.id" class="border-b pb-4">
              <el-row :gutter="20" class="items-center">
                <el-col :span="6">
                  <base-image
                      :src="item.image"
                      class="w-full h-24 object-cover rounded"
                      fit="cover"
                  />
                </el-col>
                <el-col :span="12">
                  <h3 class="text-lg font-medium">{{ item.name }}</h3>
                  <div class="text-gray-500 mt-2">
                    数量: {{ item.count }}
                  </div>
                </el-col>
                <el-col :span="6" class="text-right">
                  <div class="text-lg price">¥ {{ item.price }}</div>
                </el-col>
              </el-row>

              <!-- 评价信息 -->
              <div v-if="item.comment" class="mt-4 bg-gray-50 p-4 rounded">
                <div class="flex items-center">
                  <el-avatar :src="item.userAvatar" size="small"/>
                  <span class="ml-2">{{ item.userName }}</span>
                  <el-rate
                      v-model="item.rating"
                      class="ml-4"
                      disabled
                  />
                </div>
                <p class="mt-2 text-gray-600">{{ item.content }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script setup>
import {computed, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Select, Tickets, Van} from '@element-plus/icons-vue'
import request from '@/utils/request'
import {confirm} from "@/utils/utils.js";
import {useStore} from "vuex";
import BaseImage from "@/components/common/BaseImage.vue";

const store = useStore()
const role = computed(() => store.state.userInfo.role)
const dialogVisible = ref(false)
const orderData = ref({})
const orderItems = ref([])

// 状态映射
const getStatusText = computed(() => {
  const statusMap = {
    0: '已取消',
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成'
  }
  return statusMap[orderData.value.status] || '未知状态'
})

const getStatusType = computed(() => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'primary',
    3: 'warning',
    4: 'success'
  }
  return typeMap[orderData.value.status] || 'info'
})

let interval = null
// 打开弹窗
const open = async (orderId) => {
  await getOrder(orderId)
  if (orderData.value.status === 1) {
    interval = setInterval(() => {
      getOrder(orderId)
    }, 5000)
  }
  dialogVisible.value = true
}

const handleClose = () => {
  if (interval) {
    clearInterval(interval)
  }
}

const getOrder = async (orderId) => {
  // 获取订单详情
  orderData.value = await request.get(`/order/${orderId}`)
  // 获取订单商品列表
  orderItems.value = orderData.value.orderItems
}

// 确认发货
const orderShip = ref({})
const shipRules = {
  deliveryPerson: [{required: true, message: '请输入配送员', trigger: 'blur'}],
  deliveryPhone: [{required: true, message: '请输入配送员电话', trigger: 'blur'}]
}
const shipFormRef = ref(null)
const handleShip = async () => {
  await shipFormRef.value.validate()
  confirm('确认发货该订单吗？', async () => {
    orderShip.value.orderId = orderData.value.id
    await request.post(`/order/ship`, orderShip.value)
    await getOrder(orderData.value.id)
    ElMessage.success('发货成功')
    await open(orderData.value.id)
  })
}

// 确认收货
const handleReceive = () => {
  confirm('确认收货该订单吗？', async () => {
    await request.post(`/order/receive/${orderData.value.id}`)
    ElMessage.success('收货成功')
    await open(orderData.value.id)
  })
}

defineExpose({
  open
})
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-gray-600 {
  color: #4b5563;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.space-y-4 > * + * {
  margin-top: 1rem;
}

.border-b {
  border-bottom: 1px solid #e5e7eb;
}

.h-full {
  height: 100%;
}

.w-full {
  width: 100%;
}

.h-24 {
  height: 6rem;
}

.object-cover {
  object-fit: cover;
}

.rounded {
  border-radius: 0.25rem;
}

.p-4 {
  padding: 1rem;
}

.pb-4 {
  padding-bottom: 1rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.ml-2 {
  margin-left: 0.5rem;
}

.ml-4 {
  margin-left: 1rem;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.font-medium {
  font-weight: 500;
}

.font-bold {
  font-weight: 700;
}

.text-right {
  text-align: right;
}

.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.justify-between {
  justify-content: space-between;
}

.justify-center {
  justify-content: center;
}
</style>